package cfca.seal.util;

import cfca.com.itextpdf.text.BaseColor;
import cfca.com.itextpdf.text.DocumentException;
import cfca.com.itextpdf.text.Image;
import cfca.com.itextpdf.text.Rectangle;
import cfca.com.itextpdf.text.pdf.AcroFields;
import cfca.com.itextpdf.text.pdf.PdfContentByte;
import cfca.com.itextpdf.text.pdf.PdfReader;
import cfca.com.itextpdf.text.pdf.PdfStamper;
import cfca.sadk.util.Base64;
import cfca.seal.exception.CodeException;
import cfca.seal.front.service.ws.bean.ImageBean;
import cfca.seal.front.service.ws.util.ValidityUtil;
import cfca.seal.sadk.DonePdfSeal;
import cfca.seal.sadk.DonePdfSealUtil;
import cfca.seal.sadk.LocationInfo;
import cfca.seal.sadk.PrePdfReader;
import cfca.seal.sadk.SignatureLandscape;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PDFFieldXMLUtil
{
  private static final String FIELD = "Field";
  private static final String FIELD_IMAGE = "Image";
  private static final String FIELD_QR_CODE = "QRCodeXML";
  private static final String FILE_TYPE_TEXT = "text";
  private static final String FILE_TYPE_CHECKBOX = "checkbox";
  private static final String DEFAULT_VALUE_ZERO = "0";
  private static Map<String, String> textResults = null;
  private static Map<String, ImageBean> imageResults = null;
  private static Map<String, String> checkBoxResults = null;

  public static void getFileds(String fieldListXML, String imageListXML, int pageNoMax)
    throws CodeException
  {
    List<String> nodes = new ArrayList();
    textResults = new HashMap();
    imageResults = new HashMap();
    checkBoxResults = new HashMap();

    int index = 0;
    StringUtil.getNodesText(fieldListXML, "Field", nodes);
    for (String node : nodes) {
      String fieldType = StringUtil.getNodeText(node, "FieldType");
      String filedId = StringUtil.getNodeText(node, "FieldID");
      String fieldValue = StringUtil.getNodeText(node, "FieldValue");
      ValidityUtil.checkFields(fieldType, filedId, fieldValue);

      if ("text".equals(fieldType))
        textResults.put(filedId, fieldValue);
      else if ("checkbox".equals(fieldType)) {
        checkBoxResults.put(filedId, fieldValue);
      }
    }

    nodes = new ArrayList();
    StringUtil.getNodesText(imageListXML, "QRCodeXML", nodes);
    for (String node : nodes) {
      String qrCodeContent = StringUtil.getNodeText(node, "QRCodeContent");
      String widthString = StringUtil.getNodeText(node, "Width");
      String heightString = StringUtil.getNodeText(node, "Height");
      String pageNo = StringUtil.getNodeText(node, "PageNo");
      String lxString = StringUtil.getNodeText(node, "LX");
      String lyString = StringUtil.getNodeText(node, "LY");
      ValidityUtil.checkParamForQRCode(qrCodeContent, widthString, heightString, pageNo, lxString, lyString, pageNoMax);

      float width = Float.valueOf(widthString).floatValue();
      float height = Float.valueOf(heightString).floatValue();
      float lx = Float.valueOf(lxString).floatValue();
      float ly = Float.valueOf(lyString).floatValue();

      Image image = null;
      try {
        qrCodeContent = QRUtil.certQR(qrCodeContent);

        image = Image.getInstance(Base64.decode(qrCodeContent));
        image.setAlignment(4);
        image.setBorder(15);
        image.setBorderWidth(0.0F);
        image.setBorderColor(BaseColor.WHITE);

        image.setRotationDegrees(0.0F);
        image.setAbsolutePosition(lx, ly);
        image.scaleToFit(width, height);

        ImageBean imageBean = new ImageBean(image, "2", pageNo);
        imageResults.put(index + "", imageBean);
        index++;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    nodes = new ArrayList();
    StringUtil.getNodesText(imageListXML, "Image", nodes);
    for (String node : nodes) {
      String imageValue = StringUtil.getNodeText(node, "ImageValue");
      String imageWidth = StringUtil.getNodeText(node, "ImageWidth");
      String imageHeight = StringUtil.getNodeText(node, "ImageHeight");

      String type = StringUtil.getNodeText(node, "Type");
      ValidityUtil.checkTypeForImage(type);

      String pageNo = StringUtil.getNodeText(node, "PageNo");
      String lx = StringUtil.getNodeText(node, "LX");
      String ly = StringUtil.getNodeText(node, "LY");

      String keyword = StringUtil.getNodeText(node, "Keyword");

      String locationStyle = StringUtil.getNodeText(node, "LocationStyle");
      locationStyle = StringUtil.isEmpty(locationStyle) ? "C" : locationStyle;

      String offsetX = StringUtil.getNodeText(node, "OffsetX");
      offsetX = StringUtil.isEmpty(offsetX) ? "0" : offsetX;

      String offsetY = StringUtil.getNodeText(node, "OffsetY");
      offsetY = StringUtil.isEmpty(offsetY) ? "0" : offsetY;

      if ("2".equals(type))
        ValidityUtil.checkParamForImage(imageValue, imageWidth, imageHeight, pageNo, lx, ly, pageNoMax);
      else if ("3".equals(type)) {
        ValidityUtil.checkParamForImage2(imageValue, imageWidth, imageHeight, type, keyword, locationStyle);
      }

      try
      {
        Image image = Image.getInstance(ImageUtil.transferAlpha(Base64.decode(imageValue)));
        image.setAlignment(4);
        image.setBorder(15);
        image.setBorderWidth(0.0F);
        image.setBorderColor(BaseColor.WHITE);
        image.scaleToFit(Integer.valueOf(imageWidth).intValue(), Integer.valueOf(imageHeight).intValue());
        image.setRotationDegrees(0.0F);
        image.setAbsolutePosition(Integer.valueOf(lx).intValue(), Integer.valueOf(ly).intValue());

        ImageBean imageBean = new ImageBean(image, type, pageNo, keyword, locationStyle, offsetX, offsetY);
        imageResults.put(index + "", imageBean);
        index++;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static byte[] compoundPdfDataByImage(byte[] pdfData, Map<String, ImageBean> map)
  {
    PdfReader pdfReader = null;
    PdfStamper pdfStamper = null;
    try
    {
      for (int i = 0; i < map.size(); i++) {
        ImageBean img = (ImageBean)map.get(i + "");
        pdfReader = new PdfReader(pdfData);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        pdfStamper = new PdfStamper(pdfReader, byteArrayOutputStream);
        if ("2".equals(img.getType()))
        {
          pdfStamper.getOverContent(Integer.valueOf(img.getPageNo()).intValue()).addImage(img.getImage());
          pdfStamper.close();
          pdfReader.close();
          pdfData = byteArrayOutputStream.toByteArray();
        } else if ("3".equals(img.getType()))
        {
          String keyword = img.getKeyword();
          int keywordLength = keyword.length();
          String locationStyle = img.getLocationStyle();
          int offsetX = Integer.valueOf(img.getOffsetX()).intValue();
          int offsetY = Integer.valueOf(img.getOffsetY()).intValue();
          float scaledImageHeight = img.getImage().getScaledHeight();
          float scaledImageWidth = img.getImage().getScaledWidth();
          DonePdfSeal donePdfSeal = new DonePdfSeal();
          PrePdfReader prePdfReader = new PrePdfReader(pdfData);
          donePdfSeal.initPdfReader(prePdfReader);

          donePdfSeal.updateLocationInfoByKeyword(keyword);
          LocationInfo locationInfo = donePdfSeal.getLocationInfo();

          if (locationInfo.getCntSeal() != 0)
            for (int k = 0; k < locationInfo.getCntSeal(); k++) {
              SignatureLandscape signatureLandscape = (SignatureLandscape)locationInfo.getLocSignatureLandscapeInfoList().get(k);
              float llx = signatureLandscape.rect.getLeft();
              float lly = signatureLandscape.rect.getBottom();
              float charTextWidth = signatureLandscape.charTextWidth;
              llx = llx + charTextWidth * keywordLength / 2.0F - scaledImageWidth / 2.0F;
              lly = lly + charTextWidth / 2.0F - scaledImageWidth / 2.0F;
              if (locationStyle.equals("U")) {
                lly += charTextWidth / 2.0F;
                lly += scaledImageHeight / 2.0F;
              } else if (locationStyle.equals("D")) {
                lly -= charTextWidth / 2.0F;
                lly -= scaledImageHeight / 2.0F;
              } else if (locationStyle.equals("L")) {
                llx -= charTextWidth * keywordLength / 2.0F;
                llx -= scaledImageWidth / 2.0F;
              } else if (locationStyle.equals("R")) {
                llx += charTextWidth * keywordLength / 2.0F;
                llx += scaledImageWidth / 2.0F;
              } else if (!locationStyle.equals("C"));
              llx += offsetX;
              lly += offsetY;
              img.getImage().setAbsolutePosition(llx, lly);
              pdfStamper.getOverContent(signatureLandscape.page.intValue()).addImage(img.getImage());
              pdfStamper.close();
              pdfReader.close();
              pdfData = byteArrayOutputStream.toByteArray();
            }
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return pdfData;
  }

  private static byte[] compoundPdfDataByCheckBox(byte[] pdf, Map<String, String> checkBoxResults2)
  {
    PdfReader reader = null;
    PdfStamper stamper = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
      reader = new PdfReader(pdf);
      stamper = new PdfStamper(reader, bos);
      AcroFields form = stamper.getAcroFields();
      Set set = checkBoxResults.keySet();
      Iterator it = set.iterator();
      while (it.hasNext()) {
        String fieldId = (String)it.next();
        String fieldValue = (String)checkBoxResults.get(fieldId);
        form.setField(fieldId, fieldValue);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (null != stamper) {
          stamper.close();
        }
        if (null != reader) {
          reader.close();
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }

    return bos.toByteArray();
  }

  public static byte[] synthesizeAutoBusinessPdf(byte[] pdf, String fieldListXML, String imageListXML)
    throws IOException, DocumentException, CodeException
  {
    PrePdfReader prePdfReader = new PrePdfReader(pdf);
    int pageNoMax = prePdfReader.getPdfReader().getNumberOfPages();

    getFileds(fieldListXML, imageListXML, pageNoMax);

    byte[] result = pdf;

    if ((null != checkBoxResults) && (checkBoxResults.size() > 0)) {
      result = compoundPdfDataByCheckBox(pdf, checkBoxResults);
    }

    if ((null != imageResults) && (imageResults.size() > 0)) {
      result = compoundPdfDataByImage(result, imageResults);
    }

    if ((null != textResults) && (textResults.size() > 0)) {
      PdfReader pdfReader = new PdfReader(result);
      result = DonePdfSealUtil.createPdfByTemplate(pdfReader, textResults);
    }

    return result;
  }
}